def cols(matrix):
    assert matrix is not None and len(matrix)

    n, m = len(matrix), len(matrix[0])

    def col(j):
        for i in range(n):
            yield matrix[i][j]

    for j in range(m):
        yield col(j)


def cos_sim(a, b, eps=1e-6):
    assert a is not None and len(a)
    assert b is not None and len(b)
    assert len(a[0]) == len(b[0])
    a_norms = [sum(aij ** 2 for aij in ai) ** 0.5 for ai in a]
    b_norms = [sum(bij ** 2 for bij in bi) ** 0.5 for bi in b]
    res = [[sum(aij * bij for aij, bij in zip(ai, bj)) / (eps + a_norms[i] * b_norms[j])
            for j, bj in enumerate(b)]
           for i, ai in enumerate(a)]
    return res


def read_tsv(filename):
    res = []
    with open(filename) as f:
        for r in f:
            res.append(list(map(float, r.split('\t'))))
    return res


def write_tsv(matrix, filename):
    with open(filename, 'w') as f:
        for row in matrix:
            f.write('\t'.join(map(str, row)) + '\n')
